package org.piggy.client.support;

import lombok.extern.slf4j.Slf4j;
import org.piggy.register.center.api.RegisterCenter;
import org.piggy.client.autoconfigure.ApiProperties;
import org.piggy.common.config.ServiceDefinition;
import org.piggy.common.config.ServiceInstance;
import org.piggy.common.constants.BasicConst;

import java.util.ServiceLoader;

@Slf4j
public abstract class AbstractClientRegisterManager {

    private final ApiProperties apiProperties;

    private final RegisterCenter registerCenter;

    protected AbstractClientRegisterManager(ApiProperties apiProperties) {
        this.apiProperties = apiProperties;

        //初始化注册中心对象
        ServiceLoader<RegisterCenter> serviceLoader = ServiceLoader.load(RegisterCenter.class);
        registerCenter = serviceLoader.findFirst().orElseThrow(() -> {
            log.error("not found RegisterCenter impl");
            return new RuntimeException("not found RegisterCenter impl");
        });
        registerCenter.init(apiProperties.getRegisterAddress(), apiProperties.getEnv());
    }

    protected void register(ServiceDefinition serviceDefinition, ServiceInstance serviceInstance) {
        registerCenter.register(serviceDefinition, serviceInstance);
    }

    public ApiProperties getApiProperties() {
        return apiProperties;
    }

    public RegisterCenter getRegisterCenter() {
        return registerCenter;
    }

    protected ServiceInstance makeServiceInstance(String localIp, int port, String serviceName, String version){
        ServiceInstance serviceInstance = new ServiceInstance();
        String serviceInstanceId = localIp + BasicConst.COLON_SEPARATOR + port;
        serviceInstance.setServiceInstanceId(serviceInstanceId);
        serviceInstance.setServiceName(serviceName);
        serviceInstance.setIp(localIp);
        serviceInstance.setPort(port);
        serviceInstance.setRegisterTime(System.currentTimeMillis());
        serviceInstance.setVersion(version);
        serviceInstance.setWeight(apiProperties.getWeight());
        return serviceInstance;
    }
}
